<template>
  <view class="container">
    <view class="search-bar">
      <uni-search-bar 
        placeholder="搜索" 
        radius="100" 
        cancelButton="none"
        bgColor="#f5f5f5"
        v-model="searchValue"
        @confirm="handleSearch"
        @clear="handleClear"
      ></uni-search-bar>
    </view>
    
    <view class="sort-tab" v-if="!isSearching">
        <text :class="{'sort-active': sortType === 'default'}" @click="changeSort('default')">综合排序</text>
        <text :class="{'sort-active': sortType === 'distance'}" @click="changeSort('distance')">距离最近</text>
        <text :class="{'sort-active': sortType === 'rating'}" @click="changeSort('rating')">评分最高</text>
      </view>
    
    <view class="merchant-list">
      <view 
        class="merchant-item" 
        v-for="(item, index) in sortedMerchantList" 
        :key="index"
        @click="navigateToDetail(item.id)"
      >
        <view class="merchant-header">
          <text class="merchant-name">{{item.name}}</text>
          <text class="merchant-distance">{{calculateDistance(item)}}m</text>
        </view>
        
        <view class="merchant-rating">
          <uni-rate 
            :value="item.rete " 
            size="14" 
            readonly
            :margin="2"
          />
          <text class="rating-score">{{item.rete}}分</text>
          <text class="rating-count">备注：{{item.description ? item.description.length : 0}}</text>
        </view>
        
        <view class="merchant-time">
          <text>营业时间：{{item.startTime}} - {{item.endTime}}</text>
        </view>
        
        <view class="merchant-address">
          <text>{{item.address}}</text>
        </view>
      </view>
      
      <view class="no-more" v-if="merchantList.length > 0">
        <text>暂无更多</text>
      </view>
      
      <view class="empty-state" v-if="merchantList.length === 0">
        <text>{{isSearching ? '未找到相关商家' : '暂无商家数据'}}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import baseUrl from '../../utils/urlConfig.js';

const merchantList = ref([]);
const userLocation = ref(null);
const searchValue = ref('');
const isSearching = ref(false);

// 进入页面监听
onLoad(() => {
  getMerchant();
  getLocation();
});

// 获取商家信息
function getMerchant() { 
  uni.request({
    url: baseUrl + '/yyq/merchant/list',
    method: 'get',
    header: {
      Authorization: uni.getStorageSync('Token')
    },
    success: (res) => {
      if(res.data && res.data.code === 200) {
        merchantList.value = res.data.rows;
      } else {
        uni.showToast({
          title: '获取商家信息失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
    }
  });
}

// 搜索商家
function searchMerchant(name) {
  isSearching.value = true;
  uni.request({
    url: baseUrl + '/yyq/merchant/search',
    method: 'get',
    data: {
      name: name
    },
    header: {
      Authorization: uni.getStorageSync('Token')
    },
    success: (res) => {
      if(res.data && res.data.code === 200) {
        merchantList.value = res.data.rows;
      } else {
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '搜索请求失败',
        icon: 'none'
      });
    }
  });
}

// 处理搜索事件
function handleSearch() {
  if (searchValue.value.trim()) {
    searchMerchant(searchValue.value.trim());
  } else {
    getMerchant();
    isSearching.value = false;
  }
}

// 处理清除搜索事件
function handleClear() {
  searchValue.value = '';
  getMerchant();
  isSearching.value = false;
}

// 获取用户位置
function getLocation() {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      userLocation.value = {
        latitude: res.latitude,
        longitude: res.longitude
      };
    },
    fail: (err) => {
      console.log('获取位置失败', err);
    }
  });
}

// 计算距离
function calculateDistance(merchant) {
  if (!userLocation.value || !merchant.latitude || !merchant.longitude) {
    return null;
  }
  
  try {
    const lat1 = parseFloat(userLocation.value.latitude);
    const lon1 = parseFloat(userLocation.value.longitude);
    const lat2 = parseFloat(merchant.latitude);
    const lon2 = parseFloat(merchant.longitude);
    
    if (isNaN(lat1) || isNaN(lon1) || isNaN(lat2) || isNaN(lon2)) {
      return null;
    }
    
    // 使用Haversine公式计算更精确的距离（单位：米）
    const R = 6371000; // 地球半径（米）
    const φ1 = lat1 * Math.PI / 180;
    const φ2 = lat2 * Math.PI / 180;
    const Δφ = (lat2 - lat1) * Math.PI / 180;
    const Δλ = (lon2 - lon1) * Math.PI / 180;
    
    const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
              Math.cos(φ1) * Math.cos(φ2) *
              Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    
    return Math.round(R * c);
  } catch (e) {
    console.error('距离计算错误:', e);
    return null;
  }
}

// 新增排序类型状态
const sortType = ref('default'); // 'default' | 'distance' | 'rating'

// 计算排序后的商家列表
const sortedMerchantList = computed(() => {
  if (!merchantList.value) return [];
  
  // 创建副本以避免修改原始数据
  const list = [...merchantList.value];
  
  switch (sortType.value) {
    case 'distance':
      // 按距离排序
      return list.sort((a, b) => {
        const distanceA = calculateDistance(a) || Infinity;
        const distanceB = calculateDistance(b) || Infinity;
        return distanceA - distanceB;
      });
    case 'rating':
      // 按评分排序（降序）
      return list.sort((a, b) => (b.rete || 0) - (a.rete || 0));
    default:
      // 默认排序（原始顺序或后端返回顺序）
      return list;
  }
});

// 排序切换方法
function changeSort(type) {
  sortType.value = type;
}

// 跳转到商家详情页
function navigateToDetail(id) {
  uni.navigateTo({
    url: `/pages/index/store/store?id=${id}`
  });
}
</script>

<style scoped>
/* 原有样式保持不变 */
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.search-bar {
  margin-bottom: 20rpx;
}

.sort-tab {
  display: flex;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
}

.sort-tab text {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s ease;
}

.sort-tab text:active {
  transform: scale(0.95);
  opacity: 0.8;
}

.sort-tab .sort-active {
  color: #007AFF;
  font-weight: bold;
}

.merchant-list {
  margin-top: 20rpx;
}

.merchant-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.merchant-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.merchant-distance {
  font-size: 24rpx;
  color: #999;
}

.merchant-rating {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.rating-score {
  font-size: 24rpx;
  color: #FF9900;
  margin-left: 10rpx;
}

.rating-count {
  font-size: 24rpx;
  color: #999;
  margin-left: 20rpx;
}

.merchant-time {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.merchant-address {
  font-size: 24rpx;
  color: #666;
}

.no-more {
  text-align: center;
  padding: 30rpx;
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  font-size: 28rpx;
  color: #999;
}
</style>